﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Media.Animation;
using System.Windows;
using CMD_DKT.BAL;
using System.Windows.Controls;
using System.Data;
using RestSharp;

namespace CMD_DKT.Utilities
{
    class StatusReview
    {
        public static Thread t = null;

        public static Solicitud sol;

        public static bool CheckIsAlive()
        {

            if (StatusReview.t != null)
            {
                return StatusReview.t.IsAlive;

            }
            return false;

        }/////////

        public static void start(TextBlock tb)
        {
            try
            {
                if (!StatusReview.CheckIsAlive())
                {
                    StatusReview.t = new Thread(() =>
                    {
                        string aux = "";

                        Action a = () => aux = tb.Text;
                        Application.Current.Dispatcher.BeginInvoke(a, System.Windows.Threading.DispatcherPriority.Background);
                        
                        Action b = () => tb.Text = "Actualizando...";
                        Application.Current.Dispatcher.BeginInvoke(b, System.Windows.Threading.DispatcherPriority.Background);
                        
                        //StatusReview.StatusReviewSol();
                        StatusReview.ReviewAllSolStatus();
                        Thread.Sleep(3000);

                        //string fecha = Solicitud.WFGetLastStatusReviewDate();
                        string fecha = Solicitud.StatReviewGetLastDate();

                        if (string.IsNullOrEmpty(fecha))
                            fecha = aux;

                        Action c = () => tb.Text = fecha;
                        Application.Current.Dispatcher.BeginInvoke(c, System.Windows.Threading.DispatcherPriority.Background);

                    });

                    StatusReview.t.IsBackground = true;


                    StatusReview.t.Start();

                }

            }
            catch (Exception ex)
            {
                throw ex;

            }

            //return solicitud;

        }

        private static void ReviewAllSolStatus()
        {
            DataTable dt = new DataTable();
            bool bandera = false ;
            Dictionary<string, string> Sol = new Dictionary<string, string>();

            try
            {
                // se obtienen los datos de la tabla de Detalle
                dt = Solicitud.GetSolProceso(3);

                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        Sol = Solicitud.CallWCFService(AppConfs.WCFService, "GetDataSolStatusRol", new { unidSolicitud = dt.Rows[i]["UNID_SOLICITUD"].ToString() });
                        if (Sol.Keys.Contains("ERROR") || Sol.Keys.Contains("Exception"))
                            continue;
                        SetSolicitudChanges(Sol, dt.Rows[i]);
                        bandera=true;
                    }
                }
                if (bandera) UpdateDate();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private static void UpdateDate()
        {
            Solicitud.UpdateLastUpdate();
        }

        private static void SetSolicitudChanges(Dictionary<string, string> Sol, DataRow Row)
        {
            Solicitud UpdSol = new Solicitud() ;
            Dictionary<string, string> param = new Dictionary<string, string>();
            try
            {
                int resultset;
                if (Sol.Keys.Count > 3)
                {
                    seyDictionaryParameters(Sol, UpdSol);
                    resultset=((DataSet)UpdSol.UpsertData()).Tables.Count;
                    if (Sol.Keys.Contains("sol_idSolStat"))
                        if (resultset == 0 && Sol["sol_idSolStat"].ToString() == "6")
                        {
                            Solicitud.UpdateRechSols(Sol["unidSolicitud"]);
                        }

                }
                else
                {
                    UpdSol.UpdateSolStatus(long.Parse(Sol["UNID_SOLICITUD"].ToString()), Int32.Parse(Sol["ID_SOLICITUD_STATUS"].ToString()), long.Parse(Sol["UNID_ROL"].ToString()));
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private static void seyDictionaryParameters(Dictionary<string, string> Sol,Solicitud UpdSol)
        {
            try
            {
                foreach (KeyValuePair<string, string> p in SolStructure())
                {
                    if (Sol.Keys.Contains(p.Key.ToString()))
                        UpdSol.SetDictionaryParameterValues(p.Key.ToString(), Sol[p.Key.ToString()]);
                }//foreach
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        private static void StatusReviewSol()
        {
            DataTable dt = new DataTable();
            Dictionary<string, string> param = new Dictionary<string, string>();
            Dictionary<string, string> paramLocal = new Dictionary<string, string>();
            string parametros = "";

            try
            {
                // se obtienen los datos de la tabla de Detalle
                dt= Solicitud.WFGetInfoDetalle();

                if (dt.Rows.Count > 0)
                {
                    // se arma el diccionario
                    for (int j = 0; j < dt.Rows.Count; j++)
                    {
                        param.Clear();
                        parametros="";
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            switch (dt.Columns[i].ColumnName)
                            {
                                case "UNID_SOLICITUD":
                                    param.Add(dt.Columns[i].ColumnName, dt.Rows[j][i].ToString());
                                    paramLocal.Add("@UnidSoliciud", dt.Rows[j][i].ToString());
                                    break;
                                case "UNID_ROL":
                                    param.Add(dt.Columns[i].ColumnName, Convert.ToInt64(dt.Rows[j][i]).ToString());
                                    paramLocal.Add("@UnidRol", dt.Rows[j][i].ToString());
                                    break;
                                case "ID_SOLICITUD_STATUS":
                                    param.Add(dt.Columns[i].ColumnName, Convert.ToInt32(dt.Rows[j][i]).ToString());
                                    paramLocal.Add("@IdStatus", dt.Rows[j][i].ToString());
                                    break;
                                case "FECHA":
                                    
                                    param.Add(dt.Columns[i].ColumnName, dt.Rows[j][i].ToString());
                                    paramLocal.Add("@Fecha", dt.Rows[j][i].ToString());
                                    break;
                                case "WUSER":
                                    param.Add(dt.Columns[i].ColumnName, dt.Rows[j][i].ToString());
                                    paramLocal.Add("@User", dt.Rows[j][i].ToString());
                                    break;
                                case "WUSER_MAIL":
                                    param.Add(dt.Columns[i].ColumnName, dt.Rows[j][i].ToString());
                                    paramLocal.Add("@UserMail", dt.Rows[j][i].ToString());
                                    break;
                            }
                        }
                        // serializa diccionario
                        string paramSerial = Solicitud.SerializeParamWCFService(param);

                        // llamada al Servicio web que inserta en la tabla de detalle
                        // TODO: revisar la ejecución del servicio 
                        param=CallWCFService(AppConfs.WCFService, "InsertDetalle", paramSerial);

                        // TODO:  insert en tabla de detalles local
                        //Solicitud.WFInsertDetalle(paramLocal);
                    }

                }



                //sol.dsSolicitud.Tables[
            }
            catch (Exception ex)
            {
                throw ex;
            }
            
        }/////////



        private static Dictionary<string, string> CallWCFService(string service, string resource, string parametros)
        {
            Dictionary<string, string> res;

            try
            {
                var client = new RestClient(service);
                client.Authenticator = new HttpBasicAuthenticator("administrator", "Passw0rd1!");//new SimpleAuthenticator("username", "win-65ate595ire\\administrator", "password", "Passw0rd1!");
                //client.Authenticator = new NtlmAuthenticator();

                //new HttpBasicAuthenticator("win-65ate595ire\\administrator", "Passw0rd1!");

                var request = new RestRequest(Method.POST);
                request.Resource = resource;
                request.RequestFormat = RestSharp.DataFormat.Json;

                request.AddHeader("Content-type", "application/json");

                request.AddParameter("parametrosDocs",parametros);

                IRestResponse response = client.Execute(request);

                try
                {
                    if (response.ErrorException == null)
                        res = Solicitud.DeserializeResponseWCFServide(response.Content);
                    else
                    {
                        res = new Dictionary<string, string>();
                        res.Add("ERROR", response.ErrorException.Message);
                    }
                }
                catch (Exception ex)
                {
                    res = new Dictionary<string, string>();
                    res.Add("Exception", ex.Message);
                }

                return res;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        private static Dictionary<string, string> SolStructure()
        {
            Dictionary<string, string> Sol= new Dictionary<string,string>();
            //Sol.Add("docInfo_unidDocInfo", "");
            Sol.Add("sol_idTipoSol", "");
            Sol.Add("sol_idPrio", "");
            Sol.Add("sol_idSolStat", "");
            Sol.Add("doctos_unidDoctos", "");
            Sol.Add("unidSolicitud", "");
            Sol.Add("datsol_unidSolicitudDatos", ""); 
            Sol.Add("datsol_unidTipoSolicitante", "");
            Sol.Add("datsol_isMismoDomicilio", "");
            Sol.Add("datsol_isProveedor",  "");
            Sol.Add("datsol_isOtrasCategorias", "");
            Sol.Add("datsol_isOtrosClientes",  "");
            Sol.Add("datsol_idTipoPersonaFiscal", "");
            Sol.Add("datgral_unidSolicitud", "");
            Sol.Add("datgral_idTipoNeg", "");
            Sol.Add("datgral_razonSocial",  "");
            Sol.Add("datgral_rfc",  "");
            Sol.Add("datgral_correo",  "");
            Sol.Add("datgral_nombreSucursal",  "");
            Sol.Add("datgral_numSucursal", "");
            Sol.Add("datgral_idGrupoClientes4", "");
            Sol.Add("dirFis_unidDirFiscal", "");
            Sol.Add("dirFis_calle",  "");
            Sol.Add("dirFis_numExt",  "");
            Sol.Add("dirFis_numInt",  "");
            Sol.Add("dirFis_unidSepomex", "");
            Sol.Add("dirFis_lada",  "");
            Sol.Add("dirFis_tel", "");
            Sol.Add("dirFis_local", "");
            Sol.Add("dirEnt_unidDirEntrega", "");
            Sol.Add("dirEnt_calle",  "");
            Sol.Add("dirEnt_numExt",  "");
            Sol.Add("dirEnt_numInt",  "");
            Sol.Add("dirEnt_unidSepomex",  "");
            Sol.Add("dirEnt_lada",  "");
            Sol.Add("dirEnt_tel",  "");
            Sol.Add("dirEnt_local",  "");
            Sol.Add("datRFV_unidRFV", "");
            Sol.Add("datRFV_ter",  "");
            Sol.Add("datRFV_idLeadTime", "");
            Sol.Add("datRFV_subdir", "");
            Sol.Add("datRFV_geren",  "");
            Sol.Add("datRFV_idClo",  "");
            Sol.Add("datDPV_unidDPV", "");
            Sol.Add("datDPV_nom", "");
            Sol.Add("datDPV_tel", "");
            Sol.Add("datDPV_titulo",  "");
            Sol.Add("datDPV_correo",  "");
            Sol.Add("datDPV_idZona",  "");
            Sol.Add("datDPV_diasCol",  "");
            Sol.Add("datDPV_diasEnt",  "");
            Sol.Add("datDPV_idMedCol",  "");
            Sol.Add("datDPV_idFrec", "");
            Sol.Add("datDPV_grupoPrecio", "");
            Sol.Add("datDPV_idIva",  "");
            Sol.Add("infoad_unidInfoad", "");
            Sol.Add("infoad_respoFDV", "");
            Sol.Add("infoad_numEmpleado", "");
            Sol.Add("datBnc_unidBanc", "");
            Sol.Add("datBnc_idBanc",  "");
            Sol.Add("datBnc_ctaBanc",  "");
            Sol.Add("datBnc_suc", "");
            Sol.Add("sol_numCte", "");
            Sol.Add("sol_nomCte", "");
            return Sol;
        }

    }//end class
}
